﻿//#define DEBUG
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace AssetBundleHelper{
	public struct WWWLoadData{
		public string url;
		public System.Action<WWW> callback;
		public System.Action<WWW> downloadcallback;
		public void CallBack(WWW www){
			if (callback != null) {
				callback (www);
			}
		}
	}
	public class WWWMgr : MonoBehaviour {
		static WWWMgr instance;
		public static WWWMgr Instance{
			get{
				if (instance == null) {
					instance = new GameObject ("WWWMgr").AddComponent<WWWMgr> ();
					GameObject.DontDestroyOnLoad (instance);
				}
				return instance;
			}
		}

		public List<WWWLoader> loaders = new List<WWWLoader>();
		public void Load(string url,System.Action<WWW> callback){
			Load (url, null, callback);
		}
		public void Load(string url,System.Action<WWW> downloadcallback,System.Action<WWW> callback){
			var data = new WWWLoadData ();
			data.url = url;
			data.callback = callback;
			data.downloadcallback = downloadcallback;
			WWWLoader loader;
			if (loaders.Count > 0) {
				loader = loaders [0];
				loaders.RemoveAt (0);
			} else {
				loader = new GameObject ("wwwloader").AddComponent<WWWLoader> ();
				loader.transform.parent = transform;
			}
			loader.StartCoroutine(loader.Load (data));
		}

		public void Despawn(WWWLoader loader){
			loaders.Add (loader);
		}
	}

	public class WWWLoader:MonoBehaviour{
		System.Action<WWW> updateingcallback;
		WWW www;
		public IEnumerator Load(WWWLoadData data){
			#if DEBUG
			Debug.Log(string.Format(" start www load:{0}",data.url));
			#endif
			updateingcallback = data.downloadcallback;
			www = new WWW (data.url);
			yield return www;
			if (www.error != null) {
				Debug.Log (www.error);
			} else {
				data.CallBack (www);
			}
			updateingcallback = null;
			WWWMgr.Instance.Despawn (this);
		}
		public void Update(){
			if (www != null && updateingcallback != null) {
				updateingcallback (www);
			}
		}
	}
}
